﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

using FCNS.KeepMoney.Util;

namespace FCNS.KeepMoney.UI
{
    public partial class UserUI : Control
    {
        public UserUI()
        {
            InitializeComponent();

            this.SetStyle(ControlStyles.DoubleBuffer, true);
            this.SetStyle(ControlStyles.UserPaint, true);
            this.SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.SetStyle(ControlStyles.UserMouse, true);
            this.SetStyle(ControlStyles.ResizeRedraw, false);
            this.SetStyle(ControlStyles.Opaque, true);
        }

        Bitmap offBmp = null;

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            e.Graphics.DrawImage(offBmp, 0, 0);
        }

        protected override void OnResize(EventArgs e)
        {
            base.OnResize(e);

            if (this.Height < 10)
                this.Height = 10;
            if (this.Width < 10)
                this.Width = 10;

            RePaint();
        }

        private void RePaint()
        {
            if ((this.ClientRectangle.Width < 1) || (this.ClientRectangle.Height < 1))
                return;

            if ((offBmp == null) || (offBmp.Height != this.ClientRectangle.Height) || (offBmp.Width != this.ClientRectangle.Width))
            {
                if (offBmp != null)
                    offBmp.Dispose();

                offBmp = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);
            }

            Graphics g = PaintBackGround();
            g.Dispose();
            Paint2();
        }

        private Graphics PaintBackGround()
        {
            Graphics g = Graphics.FromImage(offBmp);
            g.Clear(Color.Red);

            return g;
        }

        private void Paint2()
        {
            if ((offBmp == null) || (offBmp.Height != this.ClientRectangle.Height) || (offBmp.Width != this.ClientRectangle.Width))
            {
                RePaint();
                return;
            }
            if ((this.ClientRectangle.Width < 1) || (this.ClientRectangle.Height < 1))
                return;

            if (!this.IsDisposed)//取消这里会导致控件无法刷新,不加验证在切换模式的时候会报错
            {
                Graphics drawingSurface = Graphics.FromHwnd(this.Handle);
                drawingSurface.DrawImage(offBmp, 0, 0);
                drawingSurface.Dispose();
            }
        }
    }
}
